import argparse
import asyncio
import sys
from typing import List, Optional

from fastapi_utils.tasks import repeat_every
from hypercorn.asyncio import serve
from hypercorn.config import Config
from py_eureka_client import eureka_client
from re_common.baselibrary.utils.baseip import BaseIp

from app_main import sets, app


# 周期性任务
@app.on_event("startup")
@repeat_every(seconds=20, raise_exceptions=True)
async def periodic():
    if not hasattr(app.state, "port") or not isinstance(app.state.port, int):
        print("app没有 port 属性")
        return False
    ip_port = app.state.ip + ":" + str(app.state.port)
    version = sets.VERSION
    tags = app.state.tags
    sql = "insert into server_address(ip_port,count,tags,version) values ('%s',1,'%s','%s') on duplicate key update count = count +1,tags = '%s',version = '%s'" % (
        ip_port, tags, version, tags, version)
    from apps.crawler_platform.util.sqlhelper import SQLHelper
    await SQLHelper.execute_commit(sql)


def setEureka(server_port, app_name):
    server_host = str(BaseIp().GetLocalIPByPrefix("192.168"))
    server_port = server_port
    eureka_client.init(eureka_server="http://192.168.31.165:19000/eureka/",
                       app_name=app_name,
                       # 当前组件的主机名，可选参数，如果不填写会自动计算一个，如果服务和 eureka 服务器部署在同一台机器，请必须填写，否则会计算出 127.0.0.1
                       instance_host=server_host,
                       instance_port=server_port,
                       # 调用其他服务时的高可用策略，可选，默认为随机
                       ha_strategy=eureka_client.HA_STRATEGY_RANDOM)


def start(sys_args: Optional[List[str]] = None) -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--port",
        dest="port",
        help=""" 设置服务的端口 """,
        default=8001,
        action="store",
        type=int,
    )

    parser.add_argument(
        "--tags",
        dest="tags",
        help=""" 设置服务的标签,如果不用main，自己的服务请携带test """,
        default="main",  # main
        action="store",
    )

    parser.add_argument(
        "--app_name",
        dest="app_name",
        help=""" 设置Eureka服务的服务名 """,
        default="fastapi-cjserver",
        action="store",
        choices=['fastapi-cjserver', 'fastapi-cjserver-test'],
    )

    args = parser.parse_args(sys_args or sys.argv[1:])
    port = args.port
    app_name = args.app_name
    tags = args.tags
    try:
        setEureka(port, app_name)
    except Exception as e:
        print(e)
    config = Config()
    config.bind = ['0.0.0.0:' + str(port)]
    config.access_log_format = '%(R)s %(s)s %(st)s %(D)s %({Header}o)s'
    config.accesslog = "-"
    config.use_reloader = True
    # config.workers = 10  # 默认为1
    config.loglevel = 'INFO'
    app.state.port = port
    app.state.tags = tags

    asyncio.run(serve(app, config))


if __name__ == '__main__':
    start()

# hypercorn test:app --worker-class trio --reload --access-logformat "%(R)s %(s)s %(st)s %(D)s %({Header}o)s" --access-logfile - -b 0.0.0.0:8000


# hypercorn test:app --reload --access-logformat "%(R)s %(s)s %(st)s %(D)s %({Header}o)s" --access-logfile - -b 0.0.0.0:8000
# 启动命令
# (端口号，默认不输入参数为8000) (tags,默认为main,测试需更改为test，正常使用为main)   (app_name，默认fastapi-cjserver)
# python main_h.py --port 8001 --tags main --app_name fastapi-cjserver
